import { ChatContext } from '@/app/chat-context';
import { apiInterceptors, postChatModeParamsList, getApplication } from '@/client/api';
import { IDB } from '@/types/chat';
import { dbMapper } from '@/utils';
import { useAsyncEffect } from 'ahooks';
import { Select } from 'antd';
import { useContext, useEffect, useMemo, useState } from 'react';
import DBIcon from '@/components/common/db-icon';

function DBSelector() {
  const { scene, dbParam, setDbParam } = useContext(ChatContext);

  const [dbs, setDbs] = useState<IDB[]>([]);

  useAsyncEffect(async () => {
    // const [, res] = await apiInterceptors(postChatModeParamsList(scene as string));
    const [, res] = await apiInterceptors(getApplication({ page_num: 1, page_size: 9999 }));
    setDbs(res.data ?? []);
  }, [scene]);

  const dbOpts = useMemo(
    () =>
      dbs.map?.((db: any) => {
        // return { name: db.param, ...dbMapper[db.type] };
        return { name: db.name, id: db.id };
      }),
    [dbs],
  );

  useEffect(() => {
    if (dbOpts?.length && !dbParam) {
      setDbParam(dbOpts[0].id);
    }
  }, [dbOpts, setDbParam, dbParam]);

  if (!dbOpts?.length) return null;

  return (
    <Select
      value={dbParam}
      className="w-36"
      onChange={(val) => {
        setDbParam(val);
      }}
    >
      {dbOpts.map((item) => (
        <Select.Option key={item.id}>
          {/*<DBIcon width={24} height={24} src={item.icon} label={item.label} className="w-[1.5em] h-[1.5em] mr-1 inline-block mt-[-4px]" />*/}
          {item.name}
        </Select.Option>
      ))}
    </Select>
  );
}

export default DBSelector;
